#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
from __future__ import print_function

# Nao 功能模块导入
from naoqi import ALProxy

# 导入数据库
from .. import db
from . import proxyManger

# Nao 机器人模型
class Nao(db.Model):
    __tablename__ = 'naos'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),unique=True)
    IP = db.Column(db.String(64),default='127.0.0.1')
    PORT = db.Column(db.Integer,default=9559)
    # db.relationship 形成一对多关系，一个Nao有两个Cam
    # 一个Cam只有一个Nao与之对应，myCam.nao
    # lazy='subquery' 立即加载，但使用子查询
    cams = db.relationship('Cam',backref='nao', lazy='immediate')
    # 通过传递 uselist=False 变为一对一关系
    # 一个Nao只有一个motion与之对应
    motion = db.relationship('Motion',uselist=False,backref='nao', lazy='immediate')
    #motion = db.relationship('Motion',backref='nao')
    
    def __init__(self,name,IP,PORT):
        from .Cam import Cam
        from .Motion import Motion
        self.name = name
        self.IP = IP
        self.PORT = PORT
        db.session.add(self)
        db.session.add(Cam(nao=self,position=u'top'))
        db.session.add(Cam(nao=self,position=u'bottom'))
        db.session.add(Motion(nao=self))

    def __repr__(self):
       return "<Nao('%s')>" % (self.name)

    @classmethod
    def get_by_name(cls,name):
        out = cls.query.filter_by(name=name).first()
        return out

    @classmethod
    def get(cls,id):
        out = cls.query.get(id)
        return out

    @classmethod
    def get_names(cls):
        db_names = db.session.query(cls.name).all()
        names = []
        for name in db_names:
            names.append(name.name)
        return names

    def delete(self):
        for cam in self.cams:
            for image in cam.images:
                image.remove_image()
                db.session.delete(image)
            db.session.delete(cam)
        db.session.delete(self.motion)

    def _get_ip(self):
        return str(self.IP)

    def _get_port(self):
        """在提交前整数变量默认是None，而不是 default 值"""
        if self.PORT is None:
            self.commit()
        return self.PORT

    def get_cam(self,position):
        for cam in self.cams:
            if str(cam.position) == str(position):
                return cam
        return None

    def _get_proxy(self,proxy_name):
        if not proxyManger.has(self.name + proxy_name):
            ip = self._get_ip()
            port = self._get_port()
            proxyManger.add(self.name + proxy_name,ALProxy(proxy_name, ip, port))
        return proxyManger.get(self.name + proxy_name)

    def get_camProxy(self):
        return self._get_proxy("ALVideoDevice")

    def get_motionProxy(self):
        return self._get_proxy("ALMotion")

    def get_postureProxy(self):
        return self._get_proxy("ALRobotPosture")

    def get_autonomousLifeProxy(self):
        return self._get_proxy("ALAutonomousLife")

    def get_LEDPorxy(self):
        return self._get_proxy("ALLeds")